require('dotenv').config();

var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');
var cors = require('cors');
const { cleanupCompletedOrders } = require('./cleanup-orders');

// 添加这一行来引入数据库连接
require('./DB/index');

var indexRouter = require('./routes/index');
var FJRouter = require('./routes/FJ');
var JJKRouter = require('./routes/JJK');
var LLZRouter = require('./routes/LLZ');
var ZPFRouter = require('./routes/ZPF');
var difyRouter = require('./routes/dify')
var app = express();
app.use(cors());
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');

app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));

app.use(express.static(path.join(__dirname, 'public')));

app.use('/', indexRouter);
app.use('/fj', FJRouter);
app.use('/jjk', JJKRouter);
app.use('/llz', LLZRouter);
app.use('/zpf', ZPFRouter);
app.use('/dify', difyRouter);
// catch 404 and forward to error handler
app.use(function(req, res, next) {
  next(createError(404));
});

// error handler
app.use(function(err, req, res, next) {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};

  // render the error page
  res.status(err.status || 500);
  res.render('error');
});

// 启动定时清理任务（每天凌晨2点执行）
function startCleanupSchedule() {
  const now = new Date();
  const tomorrow = new Date(now);
  tomorrow.setDate(tomorrow.getDate() + 1);
  tomorrow.setHours(2, 0, 0, 0); // 设置为明天凌晨2点
  
  const timeUntilTomorrow = tomorrow.getTime() - now.getTime();
  
  // 首次执行
  setTimeout(() => {
    cleanupCompletedOrders().catch(console.error);
    
    // 之后每24小时执行一次
    setInterval(() => {
      cleanupCompletedOrders().catch(console.error);
    }, 24 * 60 * 60 * 1000); // 24小时
  }, timeUntilTomorrow);
  
  console.log(`订单清理任务已启动，将在 ${tomorrow.toLocaleString()} 首次执行`);
}

// 启动清理调度
startCleanupSchedule();
module.exports = app;
